

/*
 * @name: 
 * @Author: 刘大可
 * @Date: 2023-04-30 21:29:40
 * @LastEditors: 刘大可
 * @LastEditTime: 2025-01-10 23:50:07
 */

import tips from "./tips";
import {
    HTTP_REQUEST_URL,
    HEADER,
    TOKENNAME,
    HEADERPARAMS
} from '@/config/app';

var requestTask = []
export default {

    URL: HTTP_REQUEST_URL,
    async request(data = {}, path = "", method = "POST", header = {
    }) {
        if (header.type == "json") {
            header['content-type'] = 'application/json'
        }
        let url = path
        if (url.includes('test://')) {
            url = url.replace('test://', '/api');
        } else {
            url = path.startsWith('http') ? path : this.URL + path
        }
        let arr = requestTask.filter((item, index, arr) => {
            return item == url
        })
        // let url =this.URL + path
        let token = uni.getStorageSync('token') || ""
        // token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbGllbnQueGhhZG1pbiIsImF1ZCI6InNlcnZlci54aGFkbWluIiwiaWF0IjoxNjU4NDYyMDA4LCJleHAiOjE2NTk3NTgwMDgsInVpZCI6MzI3Njl9.4MdZwYQIOL1DZdcK41sv4MWDtpQoDZ6mNTIao14dQ7o"
        const res = await new Promise(async (success, fail) => {

            if (arr.length > 0) {
                success({})
                // uni.showToast({
                // 	title: '请求中',
                // 	icon: 'none'
                // })
                return
            }
            requestTask.push(url)
            header["X-Access-Token"] = token
            const requestObj = {
                url, //仅为示例，并非真实接口营员。
                data: {
                    ...data
                },
                method,
                header: {
                    'content-type': 'application/x-www-form-urlencoded',
                    // 'content-type': 'multipart/form-data',
                    // Content-Type(默认为text/plain),name(控件name)等信息，并加上分割符(boundary).
                    // 'content-type': 'application/json',
                    // 'Allow':"POST"
                    // 'content-type': 'application/form-data',
                    // 'content-type': 'multipart/form-data',
                    // /api/userRegister

                    type: 1,
                    ...header,
                    // #ifdef MP-WEIXIN
                    // Wcode: await this.getWxCode(),
                    // #endif
                    // channel: uni.getChannel().channel
                    // "api-type": "wxapp",
                    // Content-Type: 
                    // 'content-type': 'multipart/form-data',
                    // applicationId: 'groupbuy-mobile',
                },
                success: (res) => {
                    // console.log(res);
                    // res = JSON.parse(JSON.stringify(res).replace(/http:\/\/0\.0\.0\.0:8000/g, config.baseURL));


                    if (res.statusCode == 200 || res.statusCode == 201) {

                        console.log(res);
                        
                        res.data.msg = res.data.message
                        res.data.data = res.data.data
                        delete res.data.result
                        delete res.data.message
                        // || res.data.code == 201
                        if (res.data.msg == "Token失效，请重新登录!") {
                            // res.data.msg = "请先登录"
                            // uni.removeStorageSync('token')
                            uni.clearStorageSync()
                            tips.tips(res.data.msg).then(res => {
                                console.log('跳转登录');
                                // this.middle.go('/pages/login/login')
                                // uni.navigateTo({ url: '/pages/login/login' })
                            })
                            // success(res.data)
                            return false
                        }
                        res.data.code = res.data.code == 1 ? 200 : res.data.code
                        if (res.data.code == 200) {
                            if (res.data.show == 1) {
                            }
                            success(res.data)
                        } else {
                            // 特殊的体术过滤掉
                            console.log(res.data)
                            if (res.data.msg == "您已被他人邀请") {
                                success(res.data)
                                return false
                            }
                            tips.tips(res.data.msg)
                            success(res.data)

                        }
                    } else {
                        console.log(res);
                        if (res.data.code == 401) {
                            uni.clearStorageSync()
                            tips.tips(res.data.message).then(res => {
                                console.log('跳转登录');
                                // this.go('/pages/login/login')
                                this.go('/pages/login/captcha')

                            })

                        } else {
                            uni.showToast({
                                title: "服务器错误，稍后重试！",
                                duration: 2000,
                                icon: "none",
                                success: res => {
                                    // success(res)
                                }
                            });
                        }

                        success({ code: 404, msg: "服务器错误，稍后重试！" })
                    }
                },
                fail: (err) => {
                    console.log(err)
                    fail(err)
                },
                complete: () => {
                    requestTask = requestTask.filter((item, index, arr) => {
                        return item != url
                    })
                }
            };
            uni.request(requestObj);
        })

        return res;
    },

    async requestForm(data = {}, path = "", method = "POST") {
        let header = {
            "content-type": "multipart/form-data",
        }
        this.request(data, path, method, header)
    },
    async get(path = "", data = {}, header = {}) {
        return this.request(data, path, "GET", header)
    },
    async post(path = "", data = {}, header) {
        return this.request(data, path, "POST", header)
    },
    async post2(path = "", data = {}, header) {
        header = {
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
            ...header,
        }
        return this.request(data, path, "POST", header)
    },
    async postJson(path = "", data = {}, header) {
        header = {
            "content-type": "application/json",
            ...header,
        }
        return this.request(data, path, "POST", header)
    },
    getWxCode() {
        return new Promise((resolve, reject) => {
            // #ifdef H5
            return resolve(false)

            // #endif
            uni.login({
                provider: "weixin",
                success: (result) => {
                    resolve(result.code)
                },
                fail: (error) => {
                    reject(false)
                }
            })

        })
    },

    upload(filePath = "", type = "image") {
        let token = uni.getStorageSync('token') || ""
        return new Promise((resolve, reject) => {
            console.log(filePath);
            uni.uploadFile({
                url: config.baseURL + '/upload/uploadFile',
                header: {
                    token: uni.getStorageSync('token'),
                    type: 1,
                    "X-Access-Token": token

                },
                fileType: 'image',
                filePath,
                name: 'file',
                success: ({ data, statusCode }) => {
                    if (statusCode == 200) {
                        console.log(data);

                        try {
                            data = JSON.parse(data)
                        } catch (error) {
                            tips.tips(data)
                        }
                        data.code = data.code == 1 ? 200 : data.code
                        if (data.code == 200) {
                            resolve(data.result
                            )
                        } else {
                            tips.tips(data.msg)

                        }

                    } else {

                    }
                },
                fail: (error) => {

                    resolve(error)
                }
            })
        })
    }
}